import { Component, OnInit, Input } from '@angular/core';

import { Storage } from '@ionic/storage';

import { NavController, ActionSheetController, AlertController } from 'ionic-angular';
import { Config } from '../../../../providers/config';

import { Common } from '../../../../providers/common';
import { DomSanitizer } from '@angular/platform-browser';
import _ from 'lodash';
import { MarketinghMobileAnaylListService } from "./list.service";

@Component({
  selector: 'page-marketing-mobileanaly-list',
  templateUrl: './list.html',
  providers: [MarketinghMobileAnaylListService]
})
export class MarketingMobileAnalyListPage {
  moa_page_name: any = "page-marketing-mobileanaly-list";
  moa_page_explain: any = "移动营销分析";

  Title_CompanyScaleTrend = {
    all_capitalColor: "",
    gm_capitalColor: "",
    sb_capitalColor: "",
    zh_capitalColor: "",
    all_capital: null,
    all_capitalDiff: null,
    gm_capital: null,
    gm_capitalDiff: null,
    sb_capital: null,
    sb_capitalDiff: null,
    zh_capital: null,
    zh_capitalDiff: null
  };

  hasOpAuth = false;
  chartData //趋势图数据
  tableData //表格数据集合
  showleft = [];

  constructor(public navCtrl: NavController,
    public alertCtrl: AlertController,
    public listService: MarketinghMobileAnaylListService,
    private sanitizer: DomSanitizer,
    private actionSheetCtrl: ActionSheetController,
    public storage: Storage,
    public common: Common) { }


  ionViewDidEnter(): void {
    let loginid: string,
        org: string;
    this.storage.get("userInfo").then(user => {
      let that = this;
      loginid = user.loginid;
      org = user.orgname;
      let parmas = {
        "name": loginid,
        "titleid": 1001
      }
      this.listService.getAnalyDataFromRedis(parmas).subscribe((res: any) => {
        this.hasOpAuth = res.isAdmin;
        if (res.requestData) {
          this.initData(res.requestData, org);
        }
      });
    });
  }

  /**
   * 初始化表格数据
   * @param requestData 
   */
  initData(requestData, org) {

    if (requestData.data && requestData.data.length > 0) {

      //带有描述的字段移至首位
      _.forEach(requestData.data, items => {
        _.forEach(items.data, (item, index) => {
          if (item.col8) {
            let desItem = items.data[index];
            items.data.splice(index, 1);
            items.data.unshift(desItem);
            //items.data.unshift(items.data.splice(index, 1));
          }
        })
      });

      //描述内容箭头替换
      _.forEach(requestData.data, item => {
        if (item.data[0].col8) {
          let des = item.data[0].col8; //描述内容

          item.data[0].col8 = des.replace(/([^\d])\-([0-9]*[\.]*[0-9]*\S{1})/g, "$1<span class='fall'>↓ $2</span>"); //替换"-"
          item.data[0].col8 = item.data[0].col8.replace(/([^\d])\+([0-9]*[\.]*[0-9]*\S{1})/g, "$1<span class='rise'>↑ $2</span>"); //替换"+"
        }
      });

      this.chartData = _.filter(requestData.data, function (item) {
        return item["option"]["id"] == 100015;
      });

      this.tableData = _.filter(requestData.data, function (item) {
        return item["option"]["id"] != 100015;
      })

      _.forEach( this.tableData, item => {
        let leftItem = {
          "id": null,
          "col": [],
          "title": []
        }
        leftItem["id"] = item["option"]["id"];
        _.forEach( item.data, data => {
          _.forEach( data, (val, key) => {
            if((/[\u4e00-\u9fa5]+/).test(val) && key != "col8") {
              leftItem.col.push(key)
            }
          })
        })
        leftItem. col = _.uniq(leftItem.col);
        this.showleft.push(leftItem);
      })

      this.CompanyScaleTrend(this.chartData[0]['data'].slice(1)); //生成走势图
    }
    
  }

  /**
   * 公司规模走势图
   * @constructor
   */
  CompanyScaleTrend(datas) {

    this.Title_CompanyScaleTrend.all_capital = datas[datas.length - 1]["col2"];
    this.Title_CompanyScaleTrend.gm_capital = datas[datas.length - 1]["col3"];
    this.Title_CompanyScaleTrend.sb_capital = datas[datas.length - 1]["col4"];
    this.Title_CompanyScaleTrend.zh_capital = datas[datas.length - 1]["col5"];

    _.forEach(datas, data => {
      data["col1"] = data["col1"].substr(0, 4) + "-" + data["col1"].substr(4, 2)
        + "-" + data["col1"].substr(6, 2);
      data["col2"] = parseFloat(data["col2"]);
      data["col3"] = parseFloat(data["col3"]);
      data["col4"] = parseFloat(data["col4"]);
      data["col5"] = parseFloat(data["col5"]);

    });

    this.Title_CompanyScaleTrend.all_capitalDiff = this.countDiff(datas, "col2");
    this.Title_CompanyScaleTrend.gm_capitalDiff = this.countDiff(datas, "col3");
    this.Title_CompanyScaleTrend.sb_capitalDiff = this.countDiff(datas, "col4");
    this.Title_CompanyScaleTrend.zh_capitalDiff = this.countDiff(datas, "col5");

    if (this.Title_CompanyScaleTrend.all_capitalDiff.indexOf("-") > -1) {
      this.Title_CompanyScaleTrend.all_capitalColor = "greenColor";
      this.Title_CompanyScaleTrend.all_capitalDiff = this.removeSign(this.Title_CompanyScaleTrend.all_capitalDiff);
    } else {
      this.Title_CompanyScaleTrend.all_capitalColor = "redColor";
    }

    if (this.Title_CompanyScaleTrend.gm_capitalDiff.indexOf("-") > -1) {
      this.Title_CompanyScaleTrend.gm_capitalColor = "greenColor";
      this.Title_CompanyScaleTrend.gm_capitalDiff = this.removeSign(this.Title_CompanyScaleTrend.gm_capitalDiff);
    } else {
      this.Title_CompanyScaleTrend.gm_capitalColor = "redColor";
    }

    if (this.Title_CompanyScaleTrend.sb_capitalDiff.indexOf("-") > -1) {
      this.Title_CompanyScaleTrend.sb_capitalColor = "greenColor";
      this.Title_CompanyScaleTrend.sb_capitalDiff = this.removeSign(this.Title_CompanyScaleTrend.sb_capitalDiff);
    } else {
      this.Title_CompanyScaleTrend.sb_capitalColor = "redColor";
    }

    if (this.Title_CompanyScaleTrend.zh_capitalDiff.indexOf("-") > -1) {
      this.Title_CompanyScaleTrend.zh_capitalColor = "greenColor";
      this.Title_CompanyScaleTrend.zh_capitalDiff = this.removeSign(this.Title_CompanyScaleTrend.zh_capitalDiff);
    } else {
      this.Title_CompanyScaleTrend.zh_capitalColor = "redColor";
    }

    let tickPixelInterval = parseInt(_.toString(datas.length / 4));
    console.log(tickPixelInterval);
    let all_capitalDatas = _.map(datas, "col2");
    this.markPoint(all_capitalDatas, 0);
    this.markPoint(all_capitalDatas, tickPixelInterval);
    this.markPoint(all_capitalDatas, tickPixelInterval * 2);
    this.markPoint(all_capitalDatas, tickPixelInterval * 3);
    this.markPoint(all_capitalDatas, tickPixelInterval * 4);

    let gm_capitalDatas = _.map(datas, "col3");
    this.markPoint(gm_capitalDatas, 0);
    this.markPoint(gm_capitalDatas, tickPixelInterval);
    this.markPoint(gm_capitalDatas, tickPixelInterval * 2);
    this.markPoint(gm_capitalDatas, tickPixelInterval * 3);
    this.markPoint(gm_capitalDatas, tickPixelInterval * 4);

    let sb_capitalDatas = _.map(datas, "col5");
    this.markPoint(sb_capitalDatas, 0);
    this.markPoint(sb_capitalDatas, tickPixelInterval);
    this.markPoint(sb_capitalDatas, tickPixelInterval * 2);
    this.markPoint(sb_capitalDatas, tickPixelInterval * 3);
    this.markPoint(sb_capitalDatas, tickPixelInterval * 4);

    let zh_capitalDatas = _.map(datas, "col4");
    this.markPoint(zh_capitalDatas, 0);
    this.markPoint(zh_capitalDatas, tickPixelInterval);
    this.markPoint(zh_capitalDatas, tickPixelInterval * 2);
    this.markPoint(zh_capitalDatas, tickPixelInterval * 3);
    this.markPoint(zh_capitalDatas, tickPixelInterval * 4);

    // let temp = this.common.getPreMonth("2017-03-31");
    // console.log(temp);

    let elements = document.getElementsByClassName("CompanyScaleTrend");
    _.forEach(elements, el => {
      window["Highcharts"].chart({
        chart: {
          renderTo: el
        },
        title: {
          text: '',
          style: {
            "display": "none"
          }
        },
        subtitle: {
          text: "",
          style: {
            "display": "none"
          }
        },
        xAxis: {
          tickInterval: tickPixelInterval,
          gridLineWidth: 1,
          categories: _.map(datas, "col1")
        },

        yAxis: {
          tickInterval: 1000,
          title: {
            align: "high",
            rotation: 0,
            offset: 0,
            y: -20,
            x: 0,
            text: '资产(亿元)'
          },
          labels: {
            format: '{value}'
          }
        },
        navigation: {
          buttonOptions: {
            enabled: false
          }
        },
        legend: {
          width: 220,
          align: "center",
          verticalAlign: 'top',
          margin: 35,
          y: 0,
          enabled: true
        },

        tooltip: {
          shared: true,
          crosshairs: true
        },

        plotOptions: {
          series: {
            cursor: 'pointer',
            point: {
              events: {
                click: function (e) {

                }
              }
            },
            marker: {
              enabled: false,
              lineWidth: 1,
              states: {
                hover: { enabled: true }
              }
            }
          }
        },

        series: [{
          name: '资产总计',
          color: 'Crimson',
          data: all_capitalDatas
        }, {
          name: '公募资产',
          color: '#8B5A2B',
          data: gm_capitalDatas
        }, {
          name: '专户资产',
          color: 'DarkOrange',
          data: zh_capitalDatas
        }, {
          name: '社保养老金资产',
          color: 'CornflowerBlue',
          data: sb_capitalDatas
        }]

      });
    });
  }

  markPoint(datas, index) {
    if (index >= datas.length) {
      return;
    }
    datas[index] = {
      y: datas[index],
      marker: {
        enabled: true
      }
    }
  }

  countDiff(datas, fieldName) {
    let diff = null;
    let currentItem = datas[datas.length - 1];
    let currentDate = currentItem["col1"];
    let preDate = this.common.getPreMonth(currentDate);
   
    let preItem = _.find(datas, { "col1": preDate });
    if (preItem) {
      diff = (currentItem[fieldName] - preItem[fieldName]) / preItem[fieldName] * 100;
    } else {
      diff = currentItem[fieldName] * 100;
    }
    diff = diff.toFixed(2);
    return _.toString(diff) + "%";
  }

  removeSign(str: string): string {
    return str.replace(/-+/gi, "");
  }

  /**
   * 更多操作
   */
  moreOp() {
    let bottons = [{
      text: '生成',
      handler: () => {
        this.storage.get("userInfo").then(user => {
          let loginid = user.loginid;
          let org = user.orgname;
          let titleid: number = 1001;
          this.listService.generateUSPAnalyData(loginid, titleid).subscribe((res: any) => {
            if (res) {
              if (res.isSuccess) {
                this.common.alertMessage("数据生成成功！");
                this.initData(res.requestData, org);
              } else {
                this.common.alertMessage("数据生成失败！");
              }
            }
          })
          console.log('点击生成按钮');
        });
      }
    }, {
      text: '发布',
      handler: () => {
        let confirm = this.alertCtrl.create({
          title: '提示',
          message: "您确定要发布吗？",
          enableBackdropDismiss: false,
          buttons: [{
            text: '取消',
            role: 'cancel',
            handler: () => {

            }
          }, {
            text: '确定',
            handler: () => {
              this.storage.get("userInfo").then(user => {
                let loginid = user.loginid;
                let org = user.orgname;
                let titleid: number = 1001;
                this.listService.publishUSBMobileAnalyData(titleid).subscribe((res: any) => {
                  if (res) {
                    if (res.isSuccess) {
                      this.common.alertMessage("数据发布成功！");
                      this.initData(res.requestData, org);
                    } else {
                      this.common.alertMessage("数据发布失败！");
                    }
                  }
                })
              });
            }
          }]
        });
        confirm.present();
      }
    }, {
      text: '回滚',
      handler: () => {
        let confirm = this.alertCtrl.create({
          title: '提示',
          message: "您确定要回滚吗？",
          enableBackdropDismiss: false,
          buttons: [{
            text: '取消',
            role: 'cancel',
            handler: () => {

            }
          }, {
            text: '确定',
            handler: () => {
              this.storage.get("userInfo").then(user => {
                let loginid = user.loginid;
                let org = user.orgname;
                let titleid: number = 1001;
                this.listService.rollBackUSBMobileAnalyData(titleid).subscribe((res: any) => {
                  if (res) {
                    if (res.isSuccess) {
                      this.common.alertMessage("数据回滚成功！");
                      this.initData(res.requestData, org);
                    } else {
                      this.common.alertMessage("数据回滚失败！");
                    }
                  }
                })
              });
            }
          }]
        });
        confirm.present();
      }
    }, {
      text: '取消',
      role: 'cancel',
      handler: () => {
      }
    }];

    let actionSheet = this.actionSheetCtrl.create({
      title: '',
      buttons: bottons
    });
    actionSheet.present();
  }

  setBgColor(item, tableid) {

    if (tableid != 100016 && tableid != 100019 && item.l_order_no / 10 % 2 == 0) {
      return "bg-blue"
    }

    if (tableid == 100016 && item.topareaname == '非公募保有') {
      return "bg-blue"
    }
  }

  setPosition(key, tableid) {
    let leftArr = _.find(this.showleft, {id: tableid})["col"];
    if(leftArr.indexOf(key) > -1 || (tableid == 100019 && key == "topareaname" )) {
      return "showlef"
    }
  }

  getKeys(item){
    return Object.keys(item);
  }
}

@Component({
  selector: "coltrend",
  template: "<span [ngClass]='color'>{{arrow}}{{amount}}</span>"
})
export class ColTrendComponent implements OnInit {
  @Input() tableId: any
  @Input() amount: any
  @Input() column: any
  @Input() isArrow: boolean
  color: string
  arrow: string
  ngOnInit(): void {
    //配置需要设置趋势变动的列
    const trendList = [{
      tableId: "100035",
      collist: ["col4"]
    }, {
      tableId: "100036",
      collist: ["col1"]
    }, {
      tableId: "100037",
      collist: ["col1", "col4"]
    }, {
      tableId: "100039",
      collist: ["col1"]
    }, {
      tableId: "100040",
      collist: ["col1"]
    }, {
      tableId: "100041",
      collist: ["col2", "col5"]
    }, {
      tableId: "100041",
      collist: ["col2"]
    }, {
      tableId: "100042",
      collist: ["col2"]
    }];

    if (!this.amount) {
      this.amount = '--';
      return 
    }

    if (this.tableId) {
      try {
        let colArray = _.find(trendList, { tableId: this.tableId }).collist;
        if (colArray.indexOf(this.column) > -1) {
        
          this.color = this.amount[0] === '-' ? "fall" : "rise";
        }
      } catch(err) {

      }
    } else if (!this.tableId && this.isArrow) {
      this.arrow =  this.amount[0] === '-' ? "↓" : "↑";
      this.color = this.amount[0] === '-' ? "fall" : "rise";
      this.amount = this.amount.replace(/\-/g, '');
    }

  }
}


